<?php

	namespace login\model;

		require_once ("UserCredentials.php");
		require_once ("common/model/PHPFileStorage.php");
		require_once ("login/view/LoginView.php");

		class UserList
		{
			private $adminFile;

			private $users;
			private $newUserPassW;
			private $newUserName;
			private $newUser;

			public function __construct()
			{

				$this->users = array();
				$this->loadAdmin();
			}


			//MIN
			public function addUser()
			{

				$this->users[] = $this->newUser;
			}


			public function createNewUser($Name, $Passw)
			{
				$this->newUserName = new UserName($Name);

				$this->newUserPassW = Password::fromCleartext($Passw);

				$this->newUser = UserCredentials::create($this->newUserName, $this->newUserPassW);

				$this->update($this->newUser);

				$this->users[$this->newUser->getUserName()->__toString()] = $this->newUser;

				$this->update($this->newUser);

				$this->addToFile($this->newUser);
				$this->loadAdmin();

			}


			public Function userNameIsTaken($Name)
			{
				foreach ($this->users as $takenName => $takenName)
				{	
						if ($Name == $takenName)
						{
							return false;
						}
				}
				return true;
			}


			public function addToFile(UserCredentials $newUser)
			{
				$this->adminFile->writeItem($this->newUserName, $newUser->toString());

				\Debug::log("wrote new user to file", true, $newUser);
				$this->users[$this->newUserName->__toString()] = $newUser;

			}


			public function findUser(UserCredentials $fromClient)
			{

				foreach ($this->users as $user)
				{
					if ($user->isSame($fromClient))
					{
						\Debug::log("found User");
						return $user;
					}

				}
				throw new \Exception("could not login, no matching user");
			}


			public function update(UserCredentials $changedUser)
			{
				$this->adminFile->writeItem($changedUser->getUserName(), $changedUser->toString());

				\Debug::log("wrote changed user to file", true, $changedUser);
				$this->users[$changedUser->getUserName()->__toString()] = $changedUser;
			}


			private function loadAdmin()
			{

				$this->adminFile = new \common\model\PHPFileStorage("data/admin.php");

				{
					$myArray = $this->adminFile->readAll();

					foreach ($myArray as $x => $x_value)
					{

						try
						{
							$adminUserString = $this->adminFile->readItem($x);
							$admin = UserCredentials::fromString($adminUserString);

						}
						catch (\Exception $e)
						{
							\Debug::log("Could not read file, creating new one", true, $e);

							$userName = new UserName("Admin");
							$password = Password::fromCleartext("Password");
							$admin = UserCredentials::create($userName, $password);
							$this->update($admin);
						}

						$this->users[$admin->getUserName()->__toString()] = $admin;
					}

				}

			}


		}
